import { Location } from '@angular/common';
import { Injectable } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { Subject } from 'rxjs';

@Injectable({ providedIn: 'root' })
export class RouterStateService {
  private currentRouter$: Subject<string> = new Subject<string>();

  private history: string[] = [];

  constructor(private router: Router, private location: Location) {
    this.router.events.subscribe((event: any) => {
      if (event instanceof NavigationEnd) {
        const url = event.urlAfterRedirects;
        this.addHistory(url);
        this.currentRouter$.next(url);
      }
    });
  }

  back(): void {
    this.history.pop();
    if (this.history.length > 0) {
      this.location.back();
    } else {
      this.router.navigateByUrl('/');
    }
  }

  get currentRouter(): string {
    return this.getHistroyFromBack(1);
  }

  get previouRouter(): string {
    return this.getHistroyFromBack(2);
  }

  private addHistory(url: string): void {
    const length = this.history.length;
    if (length >= 1) {
      // 新加入的与最后一个相同，忽略
      if (url === this.history[length - 1]) {
        return;
      }
    }
    this.history.push(url);
    // 最多保留5个
    this.history = this.history.slice(-5);
  }

  /**
   * 从后向前获取记录
   *
   * @param num 记录数
   * @returns
   */
  private getHistroyFromBack(num: number): string {
    var url = '';
    const length = this.history.length;
    if (length >= num) {
      url = this.history[length - num];
    }
    return url;
  }
}
